/*
 * @Description:
 * @Author: fhw
 * @Date: 2022-12-13 11:25:45
 */
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants, LoginDoType, TokenDto } from './constants';
import { equals } from 'ramda';

@Injectable()
export class AdminJwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  // token验证, payload是super中曾经解析好的token信息
  async validate(payload: TokenDto) {
    if (equals(payload.type, LoginDoType.User)) return false
    //因为已经验证过token了所以在payload中进行验证用户信息是否为空
    if (!payload.username || !payload.userId) {
      return false;
    }
    return { userId: payload.userId, username: payload.username, type: payload.type };
  }
}
